package org.water.sys.web;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.water.base.entity.R;
import org.water.base.web.BaseController;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
/**
 * 缓存控制器
 * @author qzy
 *
 */
@Controller
@RequestMapping("/admin/cache")
public class CacheController extends BaseController {

	protected static Logger logger=LogManager.getLogger(CacheController.class);
	
	/**
	 * 系统缓存,主要用于spring和shiro
	 */
	private CacheManager shiroCache;
	/**
	 * 实体缓存,主要用于hibernate
	 */
	private CacheManager hibernateCache;
	
	public  CacheController()
	{
		shiroCache=CacheManager.getCacheManager("shiroCache");
		hibernateCache=CacheManager.getCacheManager("hibernateCache");
	}
	
	/**
	 * 缓存主页
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response)
	{
		return "admin/cache/cacheList";
	}
	/**
	 * 查询数据
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/qry")
	public R qry(HttpServletRequest request,HttpServletResponse response)
	{
		R bean=getBaseBean(true, "");
		HashMap<String, Object> data=new HashMap<>();
		data.put("sysCache", listCache(shiroCache));
		data.put("beanCache", listCache(hibernateCache));
		bean.setData(data);
		return bean;
	}
	/**
	 * 获取缓存数据
	 * @param cacheManager
	 * @return
	 */
	protected List<Map<String, Object>> listCache(CacheManager cacheManager)
	{
		List<Map<String, Object>> list=new ArrayList<>();
		if(cacheManager!=null)
		{
			String[] cacheNames=cacheManager.getCacheNames();
			for(int i=0;i<cacheNames.length;i++)
			{
				Cache cache=cacheManager.getCache(cacheNames[i]);
				HashMap<String, Object> map=new HashMap<>();
				map.put("name", cache.getName());
				map.put("size", cache.getSize());
				map.put("manager",cacheManager.getName());
				map.put("status", cache.getStatus().toString());
				map.put("keys", cache.getKeys());
				list.add(map);
			}
		}
		return list;
	}
	/**
	 * 查看系统类加载器已加载的类
	 */
	protected void sysClasses()
	{
		try{
			Field f=ClassLoader.class.getDeclaredField("classes");
			f.setAccessible(true);
			//系统类
			Vector<?> classes=(Vector<?>) f.get(ClassLoader.getSystemClassLoader());
			//当前类的类加载器
			Vector<?> classes2=(Vector<?>) f.get(this.getClass().getClassLoader());
			logger.info("classes size:"+classes.size());
			logger.info("classes2 size:"+classes2.size());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
